VKPlayer = (function($, self, undefined) {

    self.Selectors = {
        content:			"#content",
        mainPlayer:			"#header-player",
        jPlayerId:			"#jquery_jplayer_1",
        jPlayerContent:		"#jp_container_1"
    }

    self.Templates = {
        largePlayer:		"#tpl-player-large",
        loaderSmall:		"#tpl-loader-small",
        albumShort:			"#tpl-album-short",
        audioListItem:		"#tpl-audio-list-item",
        userShort:			"#tpl-user-short",
        userFull:			"#tpl-user-full",
        slidePager:			"#tpl-pager",
        moreTracks:			"#tpl-more-tracks",
        audioTracks:		"#tpl-audio-tracks",
        friends:			"#tpl-friends",
		downloadLinks:		"#tpl-download-links",
		downloadLink:		"#tpl-download-link",
		downloadSearchErr:	"#tpl-links-search-err",
		videoPlayerWrap:	"#tpl-video-player-wrap",
		videoThumbVk:		"#tpl-video-thumb-vk",
		videoFullVk:		"#tpl-video-full-vk",
		videoSearchErr:		"#tpl-video-search-err",
		drawError:		    "#tpl-error",
		drawTitle:		    "#tpl-title"
    }

	self.AppRouter = Backbone.Router.extend({
        routes: {
            "":									"init",
            "recommends/":						"showRecommends",
            "popular/":							"showPopular",
            "based/:hash/":						"showBased",
            "tracklist/":						"showTracklist",
            "user/:uid/tracklist/":				"showTracklist",
            "user/:uid/tracklist/:album_id/":	"showTracklist"
        },

        init: function() {
        },

        flashAnchor: function(anchor) {
            $('.anchor').removeClass('active');
            $('.anchor-' + anchor).addClass('active');
            $('.anchor-' + anchor).parents('.anchor').addClass('active');
        },

        showTracklist: function(uid, album_id) {
            var anchor = 'tracklist';
            anchor += uid ? '-' + uid : '';
            anchor += album_id ? '-' + album_id : '';
            this.flashAnchor(anchor);

            downloadingOn(10000);
            loadTracklist(uid, album_id, true);
        },

        showRecommends: function() {
            this.flashAnchor('recommends');
            downloadingOn(10000);
            var $content = $(self.Selectors.content);
            $content.addClass('loading');
            $.ajax({
                url: '/site/recommends',
                type: 'POST',
                data: {},
                dataType: 'json'
            })
			.success(function(data) {
				$content.removeClass('loading')
				.clear()
				.appendTitle({title: 'Рекомендованные'});
				if (data && ! _.isEmpty(data.tracklist)) {
					renderTracklist(data.tracklist);
				} else {
					$content
					.appendError({
						title:'Рекомендованных композиций нет',
						text: data.error_text || ''
					});
				}
			})
			.error(function(data) {
			});
            return true;
        },
		
        showPopular: function() {
            this.flashAnchor('popular');
            downloadingOn(10000);
            var $content = $(self.Selectors.content);
            $content.addClass('loading');
            $.ajax({
                url: '/site/popular',
                type: 'POST',
                data: {},
                dataType: 'json'
            })
			.success(function(data) {
				$content.removeClass('loading')
				.clear()
				.appendTitle({title: 'Популярные'});
				if (data) {
					if (! _.isEmpty(data.tracklist)) {
						renderTracklist(data.tracklist);
					}
				}
			})
			.error(function(data) {
			});
            return true;
        },

        showBased: function(hash) {

			var defaultErrorTitle = 'Похожики не найдены';
			var defaultErrorText = 'возможно для данной композиции похожие объекты не расчитаны';

            this.flashAnchor();
            downloadingOn(10000);
            var $content = $(self.Selectors.content);
            $content.addClass('loading');
            $.ajax({
                url: '/site/based',
                type: 'POST',
                data: {
					hash: hash
				},
                dataType: 'json'
            })
			.success(function(data) {
				$content.removeClass('loading')
				.clear()
				.appendTitle({title: 'Похожики'});
				if (data) {
					if (! _.isEmpty(data.tracklist)) {
						renderTracklist(data.tracklist);
					} else {
						$content.appendError({
							title: data.error_title || defaultErrorTitle,
							text: data.error_text || defaultErrorText
						});
					}
				} else {
					$content.appendError({
						title: defaultErrorTitle,
						text: defaultErrorText
					});
				}
			})
			.error(function(data) {
				$content.removeClass('loading')
				.clear()
				.appendTitle({title: 'Похожики'})
				.appendError({title: 'Похожики не найдены', text: defaultErrorText});
			});
            return true;
        }
    });

   	function loadTracklist(uid, album_id, render) {
        var modelForSave;
        var modelUser;
        var modelAlbum;
        var tracklist;

        if (render) {
            PLAYER.trigger('hide');
            var $content = $(self.Selectors.content);
            $content.addClass('loading');
			$content.clear();
        }

        if (!uid)
            var uid = USER.get('uid');

        if (USER.get('uid') == uid) {
            modelUser = USER;
        } else {
            var friends = USER.get('friends');

            if (!_.isEmpty(friends) && !friends.isEmpty())
                modelUser = _.first(friends.getById(uid));

            /* если френд и фотонвый режим.. и мы не спешим.. */
            if (!render && !_.isEmpty(modelUser))
                setTimeout(function() {
                    DEQUE.rotateUserFriends(uid)
                }, 30000);
        }

        if (!_.isEmpty(modelUser)) {
            if (album_id) {
                modelAlbum = _.first(modelUser.get('albums').getById(album_id));
                tracklist = modelAlbum.get('tracklist');
                modelForSave = modelAlbum;
            } else {
                tracklist = modelUser.get('tracklist');
                modelForSave = modelUser;
            }
        }

        if (_.isEmpty(tracklist)) {
            getAudio(uid, album_id)
                .done(function(result) {

                    if (render) {
                        $content.removeClass('loading');
                    }

                    if (_.isArray(result)) {
                        var tracks = new self.Collections.Tracks(result);
                        tracklist = new self.Models.Tracklist();
                        tracklist.linkTracks(tracks);

                        if (_.isEmpty(modelUser))
                            getProfiles(uid)
                                .done(function(result) {
                                    if (result) {
                                        modelUser = new self.Models.User(_.first(result));
                                        tracklist.set({owner: modelUser});
                                    }
                                })
                        else
                            tracklist.set({owner: modelUser});

                        if (! _.isEmpty(modelForSave))
                            modelForSave.set({tracklist: tracklist});

                        if (render) {
                            tracklist.trigger('show');
                        }

                        /* даем немного времени..
						* на подгрузку овнера в треклист...
						* нам ведь не к спеху..*/
                        setTimeout(function() {
							if (render) {
								DEQUE.pushFront(tracklist, 'tracklists');
							} else {
								DEQUE.pushBack(tracklist, 'tracklists');
							}

                        }, 7000);

                    } else {
                        if (render) {
                            $content.html('Записей нет');
                        }
                    }
                });
        } else {
            if (render) {
                $content.removeClass('loading');
            }

            if (_.isEmpty(modelUser))
                getProfiles(uid)
                    .done(function(result) {
                        if (result) {
                            modelUser = new self.Models.User(_.first(result));
                        }
                    })
            if (render) {
                tracklist.trigger('show');
            }
        }
    } //* end showTracklist */

	self.loadTracklist = loadTracklist;

    return self;
})(jQuery, VKPlayer || {});
